﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using sqlite;
using Finisar.SQLite;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Drawing;

namespace IBoLT.SettingWindows
{
    /// <summary>
    /// Логика взаимодействия для tdLBase.xaml
    /// </summary>
    public partial class tdLBase : Window
    {
        private sqliteclass mydb = new sqliteclass();// Класс  работы с БД
        DataTable datatable = null;// Класс  работы с БД
        private string sPath = "iboltLDB.db"; // Путь к базе
        private string sSql = string.Empty; // Строка запроса
        DataTable qtable = new DataTable();
        DataRow temp;
        Bitmap image;
        int mq;
        int pre;
        public tdLBase(String dbPath)
        {
			sPath = dbPath;

			InitializeComponent();
            Precision.ValueChanged += hSearch;

            CommandBinding commBind = new CommandBinding(CommandsIBoLT.cReviewDB, hReviewDB); this.CommandBindings.Add(commBind);
            commBind = new CommandBinding(CommandsIBoLT.cLoadDataInTheTable, hloadDataInTheTable); this.CommandBindings.Add(commBind);
            
			this.refresh_texgrid();
            this.refresh_texlistbox();
        }
        
		private void hReviewDB(object sender, ExecutedRoutedEventArgs e)
        {
        }
        
		private void hloadDataInTheTable(object sender, ExecutedRoutedEventArgs e)
        {
			Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

			dlg.DefaultExt = ".bmp";
			dlg.Filter = "24-разрядный рисунок (.bmp;.jpg)|*.bmp;*.jpg";
			dlg.Title = "Загрузка изображения";

			
			sSql = "SELECT id_texture,searchInfo,nameTexture,path,id_user,description  FROM tTextures";
			datatable = mydb.drExecute(sPath, sSql);



			if (dlg.ShowDialog().Value)
			{
                Precision_panel.Visibility = System.Windows.Visibility.Visible;
				image = new Bitmap(dlg.FileName);
                SeIm.Source = SystemDrawingHelper.BitmapToBitmapImage(image);
				IBoLT.HelperClasses.WMetrics metric = new HelperClasses.WMetrics(image);
				mq = metric.CWMetric();

				qtable = datatable.Copy();
				qtable.Rows.Clear();
				
				//Поисковый запрос
				
				if (datatable == null)
				{
					MessageBox.Show("Таблица пуста");
				}
				//сам поиск
				for (int i = 0; i < datatable.Rows.Count; ++i)
				{
					if (seed(mq, Convert.ToInt32(datatable.Rows[i][1]), 20)) 
					{
						temp = datatable.Rows[i];
						qtable.Rows.Add(temp.ItemArray);
					}
				}

				TexGrid.ItemsSource = qtable.DefaultView;
				TexListBox.ItemsSource = qtable.DefaultView;
			}
        }

        private bool seed(int one, int two, int proc)
        {
            double dOne = Convert.ToDouble(one);
            //MessageBox.Show(dOne.ToString());
            double dTwo = Convert.ToDouble(two);
           // MessageBox.Show(dTwo.ToString());
            double dProc = Convert.ToDouble(proc);
          //  MessageBox.Show(dProc.ToString());
            double d = dOne / 100 * dProc;
          //  MessageBox.Show(d.ToString());
			if (dTwo < (dOne + d) && dTwo > (dOne - d))
            {
                //MessageBox.Show("тру");
                return true;
            }
            else
                return false;
        }

        private void refresh_texgrid()
        {
            sSql = "select id_texture,id_user,nameTexture,description,path  FROM tTextures  ";
            //sSql = "select *  from tTextures";
            datatable = mydb.drExecute(sPath, sSql);
            if (datatable == null)
            {
                MessageBox.Show("Таблица пуста");
            }
            TexGrid.ItemsSource = datatable.DefaultView;
        }

        private void refresh_texlistbox()
        {
            sSql = "select path,nameTexture  FROM tTextures";
            datatable = mydb.drExecute(sPath, sSql);
            if (datatable == null)
            {
                MessageBox.Show("Таблица пуста");
            }

            TexListBox.ItemsSource = datatable.DefaultView;
        }

        private void hSearch(object sender, RoutedPropertyChangedEventArgs<double> e) 
        {
           pre =  Convert.ToInt32(Precision.Value);
           Precision_tb.Text = Math.Abs(100-pre).ToString();
           qtable.Rows.Clear();

           for (int i = 0; i < datatable.Rows.Count; ++i)
           {
               if (seed(mq, Convert.ToInt32(datatable.Rows[i][1]), pre))
               {
                   temp = datatable.Rows[i];
                   qtable.Rows.Add(temp.ItemArray);
               }
           }

           TexGrid.ItemsSource = qtable.DefaultView;
           TexListBox.ItemsSource = qtable.DefaultView; 
        }

    }
}
